// pages/merchant-info/merchant-info.js
const request = require('../../utils/request')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentStep: 1,
    progressWidth: 20,
    mainCategories: [
      '水产', '猪牛羊肉', '蔬菜', '冻品',
      '海鲜'
    ],
    mainCategoryIndex: 0,
    formData: {
      // 营业执照信息
      businessLicense: '',
      merchantName: '',
      creditCode: '',
      representative: '',
      registeredAddress: '',
      registeredCapital: '',
      establishDate: '',
      businessStartDate: '',
      businessEndDate: '',

      // 法人信息
      idCardFront: '',
      idCardBack: '',
      legalPersonName: '',
      legalPersonId: '',
      legalPersonPhone: '',

      // 食品经营许可证
      foodLicense: '',
      foodLicenseNumber: '',
      businessPremises: '',
      issuingAuthority: '',
      foodLicenseStartDate: '',
      foodLicenseEndDate: '',

      // 经营品类
      mainCategory: '',
      businessMode: [],
      businessBrands: '',
      annualRevenue: '',
      employeeCount: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取商户信息
    request.get('/admin-api/mini/home/getMerchantInfo', this.data.queryParam).then(res => {
      wx.hideLoading()
      if (res.code === 0) {
        if (res.data !== null) {
          this.setData({
            formData: res.data
          })
        }
      }
    })
    // 获取经营品类字典
  },

  // 上一步
  prevStep: function () {
    if (this.data.currentStep > 1) {
      const newStep = this.data.currentStep - 1;
      this.setData({
        currentStep: newStep,
        progressWidth: (newStep - 1) * 20
      });
    }
  },

  // 下一步
  nextStep: function () {
    if (this.data.currentStep < 5) {
      const newStep = this.data.currentStep + 1;
      this.setData({
        currentStep: newStep,
        progressWidth: (newStep - 1) * 20
      });
    }
  },

  // 选择营业执照
  chooseBusinessLicense: function () {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          'formData.businessLicense': res.tempFilePaths[0]
        });
        // 这里可以上传到服务器，获取永久链接
        request.upload('/admin-api/infra/file/upload', res.tempFilePaths[0]).then(res => {
          if (res.code === 0) {
            that.setData({
              "formData.businessLicense": res.data
            });
          }
        });
        // OCR识别
        wx.serviceMarket.invokeService({
          service: 'wx79ac3de8be320b71',
          api: 'OcrAllInOne',
          data: {
            // 用 CDN 方法标记要上传并转换成 HTTP URL 的文件
            img_url: new wx.serviceMarket.CDN({
              type: 'filePath',
              filePath: res.tempFilePaths[0]
            }),
            data_type: 3,
            ocr_type: 7
          },
          success: function (res) {
            console.log(111, res)
            console.log(res.data.biz_license_res.enterprise_name)
            that.setData({
              "formData.merchantName": res.data.biz_license_res.enterprise_name.text,
              "formData.registeredAddress": res.data.biz_license_res.address.text,
              "formData.representative": res.data.biz_license_res.legal_representative.text // 法人
            })

          },
          failed: (error) => {
            console.log(222, error);
            wx.showModal({
              title: 'fail',
              content: "识别失败",
            })
          }
        })
      }
    });
  },

  // 选择身份证正面
  chooseIdCardFront: function () {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          'formData.idCardFront': res.tempFilePaths[0]
        });
        // 这里可以上传到服务器，获取永久链接
        request.upload('/admin-api/infra/file/upload', res.tempFilePaths[0]).then(res => {
          if (res.code === 0) {
            that.setData({
              "formData.idCardFront": res.data
            });
          }
        });
        wx.serviceMarket.invokeService({
          service: 'wx79ac3de8be320b71',
          api: 'OcrAllInOne',
          data: {
            // 用 CDN 方法标记要上传并转换成 HTTP URL 的文件
            img_url: new wx.serviceMarket.CDN({
              type: 'filePath',
              filePath: res.tempFilePaths[0]
            }),
            data_type: 3,
            ocr_type: 1
          },
          success: function (res) {
            console.log(111, res)
            console.log(res.data.idcard_res.name.text)
            that.setData({
              "formData.legalPersonName": res.data.idcard_res.name.text,
              "formData.legalPersonId": res.data.idcard_res.id.text
            })
          },
          failed: (error) => {
            console.log(222, error);
            wx.showModal({
              title: 'fail',
              content: "识别失败",
            })
          }
        })
      }
    });
  },

  // 选择身份证反面
  chooseIdCardBack: function () {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          'formData.idCardBack': res.tempFilePaths[0]
        });
        // 这里可以上传到服务器，获取永久链接
        request.upload('/admin-api/infra/file/upload', res.tempFilePaths[0]).then(res => {
          if (res.code === 0) {
            that.setData({
              "formData.idCardBack": res.data
            });
          }
        });
      }
    });
  },

  // 选择食品经营许可证
  chooseFoodLicense: function () {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          'formData.foodLicense': res.tempFilePaths[0]
        });
        // 这里可以上传到服务器，获取永久链接
        request.upload('/admin-api/infra/file/upload', res.tempFilePaths[0]).then(res => {
          if (res.code === 0) {
            that.setData({
              "formData.foodLicense": res.data
            });
          }
        });
      }
    });
  },

  // 表单字段变更处理
  onMerchantNameChange: function (e) {
    this.setData({
      'formData.merchantName': e.detail.value
    });
  },

  onCreditCodeChange: function (e) {
    this.setData({
      'formData.creditCode': e.detail.value
    });
  },

  onRegisteredAddressChange: function (e) {
    this.setData({
      'formData.registeredAddress': e.detail.value
    });
  },

  onRegisteredCapitalChange: function (e) {
    this.setData({
      'formData.registeredCapital': e.detail.value
    });
  },

  onEstablishDateChange: function (e) {
    this.setData({
      'formData.establishDate': e.detail.value
    });
  },

  onBusinessStartDateChange: function (e) {
    this.setData({
      'formData.businessStartDate': e.detail.value
    });
  },

  onBusinessEndDateChange: function (e) {
    this.setData({
      'formData.businessEndDate': e.detail.value
    });
  },

  onLegalPersonNameChange: function (e) {
    this.setData({
      'formData.legalPersonName': e.detail.value
    });
  },

  onLegalPersonIdChange: function (e) {
    this.setData({
      'formData.legalPersonId': e.detail.value
    });
  },

  onLegalPersonPhoneChange: function (e) {
    this.setData({
      'formData.legalPersonPhone': e.detail.value
    });
  },

  onFoodLicenseNumberChange: function (e) {
    this.setData({
      'formData.foodLicenseNumber': e.detail.value
    });
  },

  onBusinessPremisesChange: function (e) {
    this.setData({
      'formData.businessPremises': e.detail.value
    });
  },

  onIssuingAuthorityChange: function (e) {
    this.setData({
      'formData.issuingAuthority': e.detail.value
    });
  },

  onFoodLicenseStartDateChange: function (e) {
    this.setData({
      'formData.foodLicenseStartDate': e.detail.value
    });
  },

  onFoodLicenseEndDateChange: function (e) {
    this.setData({
      'formData.foodLicenseEndDate': e.detail.value
    });
  },

  onMainCategoryChange: function (e) {
    const index = e.detail.value;
    this.setData({
      mainCategoryIndex: index,
      'formData.mainCategory': this.data.mainCategories[index]
    });
  },

  // 经营模式切换
  toggleBusinessMode: function (e) {
    const value = e.currentTarget.dataset.value;
    const businessMode = this.data.formData.businessMode;
    const index = businessMode.indexOf(value);

    if (index > -1) {
      businessMode.splice(index, 1);
    } else {
      businessMode.push(value);
    }

    this.setData({
      'formData.businessMode': businessMode
    });
  },

  onBusinessBrandsChange: function (e) {
    this.setData({
      'formData.businessBrands': e.detail.value
    });
  },

  onAnnualRevenueChange: function (e) {
    this.setData({
      'formData.annualRevenue': e.detail.value
    });
  },

  onEmployeeCountChange: function (e) {
    this.setData({
      'formData.employeeCount': e.detail.value
    });
  },

  // 返回上一页
  navigateBack: function () {
    wx.navigateBack();
  },

  // 提交表单
  submitForm: function () {
    const formData = this.data.formData;

    // 简单表单验证
    if (!formData.merchantName) {
      wx.showToast({
        title: '请输入商户名称',
        icon: 'none'
      });
      return;
    }

    // if (!formData.creditCode || formData.creditCode.length !== 18) {
    //   wx.showToast({
    //     title: '请输入正确的统一社会信用代码',
    //     icon: 'none'
    //   });
    //   return;
    // }

    // if (!formData.legalPersonName) {
    //   wx.showToast({
    //     title: '请输入法人姓名',
    //     icon: 'none'
    //   });
    //   return;
    // }

    // if (!formData.legalPersonId || formData.legalPersonId.length !== 18) {
    //   wx.showToast({
    //     title: '请输入正确的法人身份证号码',
    //     icon: 'none'
    //   });
    //   return;
    // }

    // 实际开发中这里应该调用API提交数据
    request.post('/admin-api/mini/home/create', this.data.formData).then(res => {
      if (res.code === 0) {
        // 显示提交成功提示
        wx.showModal({
          title: '提交成功',
          content: '您的商户信息已提交',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              // 返回上一页或跳转到其他页面
              wx.navigateBack();
            }
          }
        });
      }
    });




  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})